/**
 * Created by HackerAC on 2020-11-09.
 */
$(function () {
    //进入个人中心默认展示个人信息
    $(".selfInfo").show();

    $(".accMenu").click(function () {
        $(".order1").toggle();
    });
    $(".carMenu").click(function () {
        $(".order2").toggle();
    });
    $(".serMenu").click(function () {
        $(".order3").toggle();
    });
    $(".LeftSection ul li").click(function () {
        $(this).addClass("liActive");
        $(this).siblings().removeClass("liActive");
    });

    $("#selfInfo").click(function () {
        var selfInfo = $(".selfInfo");
        selfInfo.show();
        selfInfo.siblings().hide();
    });

    //点击提交修改密码按钮
    $("#submitModifyPwd").click(function(){
        const originPwd = $("#originPwd").val();
        const newPwd = $("#newPwd").val();
        const newPwd2 = $("#newPwd2").val();

        //密码规则正则表达式
        //密码为6-16位并且字母、数字、特殊字符三项中有两项
        const RegPwd = new RegExp("^(?=.{6,16})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
        if(originPwd===""||newPwd===""){
            alert("非法空输入！");
            return false;
        }else if(originPwd.length<6||newPwd<6){
            alert("密码长度太短");
            return false;
        }else if(!RegPwd.test(newPwd)){
            alert("密码格式有误！");
            return false;
        }else if(newPwd!==newPwd2){
            alert("两次输入的新密码不一致！");
            return false;
        }else{
            $.ajax({
                url:"modifyPwd",
                type:"post",
                data:{"originPwd":originPwd,"newPwd":newPwd},
                dataType:"json",
                success:function(result){
                    if(result===1){
                        alert("修改成功！");
                        alert("账号登录信息已变更，请重新登录！");
                        self.location="SignOut";
                    }else if(result===2){
                        alert("原密码错误！");
                    }else{
                        alert("修改失败！")
                    }
                }

            });
        }
    });

    //点击提交新个人信息按钮
    $("#submtMdfyPrsnInfo").click(function(){
        const newUsername = $("#newUsername").val();
        const newPhone = $("#newPhone").val();
        const newEmail = $("#newEmail").val();
        const newNickName = $("#newNickName").val();
        const newAddress = $("#newAddress").val();

        //正则表达式
        const UsernameReg =/^[A-Za-z0-9_]{1,12}$/;
        const mobileReg = /^1[34578]\d{9}$/;
        const emailReg = new RegExp("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\\.[a-zA-Z0-9_-]{2,3}){1,2})$");
        const nickNameReg =/^[\u4E00-\u9FA5A-Za-z0-9_]{1,16}$/;
        const addressReg =/^[\u4e00-\u9fa5]{2,}$/;

        if(!UsernameReg.test(newUsername)){
            alert("用户名格式有误！(1~12位英文字符数字下划线)");
            return false;
        }else if(!mobileReg.test(newPhone)){
            alert("手机号格式有误！");
            return false;
        }else if(!emailReg.test(newEmail)){
            alert("邮箱格式有误！");
            return false;
        }else if(!nickNameReg.test(newNickName)){
            alert("昵称不合法！(1~16位中英文字符数字下划线)");
            return false;
        }else if(!addressReg.test(newAddress)){
            alert("地址不正确！至少输入（XX市/县）!");
            return false;
        }else{
            $.ajax({
                url:"modifyPersonInfo",
                type:"post",
                data:{"newUsername":newUsername,"newPhone":newPhone,"newEmail":newEmail,"newNickName":newNickName,"newAddress":newAddress},
                dataType:"json",
                contentType: "application/json;charset=utf-8",
                success:function(result){
                    if(result==="BP"){
                        alert("修改失败！该手机号已被其他账号使用！");
                    }else if(result==="bUN"){
                        alert("修改失败！该用户名已被其他账号使用！");
                    }else if(result==="Er"){
                        alert("修改失败！服务器繁忙！");
                    }else{
                        alert("修改成功！");
                    }
                    self.location="toPersonalCenter";
                }
            });
        }
    });

    //登录日志查询
    $("#loginRecord").click(function () {
        var loginRecord = $(".loginRecord");
        loginRecord.show();
        loginRecord.siblings().hide();
        //刷新显示登陆日志表
        build_LoginRecord();
    });

    //我卖的车
    $("#mySellCar").click(function () {
        var mySellCar = $(".mySellCar");
        mySellCar.show();
        mySellCar.siblings().hide();
    });

    //我买的车
    $("#myBuyCar").click(function () {
        var myBuyCar = $(".myBuyCar");
        myBuyCar.show();
        myBuyCar.siblings().hide();
    });
    //我的收藏
    $("#myFavorite").click(function () {
        var myFavorite = $(".myFavorite");
        myFavorite.show();
        myFavorite.siblings().hide();
    });
    //我的预约
    $("#myYuYue").click(function () {
        var myYuYue = $(".myYuYue");
        myYuYue.show();
        myYuYue.siblings().hide();
    });
    //我的信审资料
    $("#myPaper").click(function () {
        var myPaper = $(".myPaper");
        myPaper.show();
        myPaper.siblings().hide();
        //刷新并显示我的信审资料列表
        build_MyCreditFiles();
    });
    //上传信用资料
    $("#submitCreditfile").click(function(){
        var file=$("#uploadfile");
        if(file.val()==""){
            alert("请选择文件！");
            return false;
        }else{
            var formData = new FormData($("#creditForm")[0]);
            $.ajax({
                url:"sentCreditFile",
                dataType:"json",
                type:"POST",
                async: false,//同步
                data: formData,
                processData : false, // 数据不做处理
                contentType : false, // 无Content-Type请求头
                success: function (resp) {
                    if(resp===1){
                        alert("上传成功！");
                        //刷新并显示我的信审资料列表
                        build_MyCreditFiles();
                    } else {
                        alert("上传失败！");
                    }
                }
                ,error:function(resp){
                    console.log(resp);
                }
            })
        }
    });

    //我的签约
    $("#myQieYue").click(function () {
        var myQieYue = $(".myQieYue");
        myQieYue.show();
        myQieYue.siblings().hide();
    });
    //我的还款
    $("#myHuanKuan").click(function () {
        var myHuanKuan = $(".myHuanKuan");
        myHuanKuan.show();
        myHuanKuan.siblings().hide();
        //刷新并显示还款记录
        build_instRecord();
    });
    //点击我要还款
    $("#wannaPayIntsl").click(function () {
        // 当期期数
        var qishu = $("#instRecordTab tbody tr:last td:first").text();
        //获取当前日期月份
        var thisDate = new Date();
        var month=(thisDate.getMonth()+1)+"";
        //获取最后一次记录的的月份
        var lastRecordMonth = $("#instRecordTab tbody tr:last td").eq(1).text();
        var lastMonth = lastRecordMonth.substring(5,7);
        if(lastMonth!==month){
            $("#thisTimes").text((parseInt(qishu)+1));
            $("#shouldPay").text($("#yuegong").text());
        }else{
            $("#thisTimes").text(parseInt(qishu));
            $("#shouldPay").text("未知");
        }
        $("#payThisInstInfo").toggle();
    });

    //点击确认还款按钮
    $("#PayInstSure").click(function(){
        const payMoney = $("#shouldPay").text();
        if(payMoney==="未知"){
            alert("本期已还或暂无具体金额!");
            return false;
        }else{
        $.ajax({
            url: "addInstRecords",
            data: "payMoney="+payMoney,
            type: "POST",
            success: function (result) {
                if(result===1){
                    alert("还款成功！");
                    //刷新并显示还款记录
                    build_instRecord();
                }else{
                    alert("还款失败！");
                }
            }
        });
        }
    });

    //养护记录
    $("#myWeiHu").click(function () {
        const myWeiHu = $(".myWeiHu");
        myWeiHu.show();
        myWeiHu.siblings().hide();
        //刷新并显示养护记录
        build_maintainRecord();
    });
    //退换记录
    $("#myTuiHuan").click(function () {
        const myTuiHuan = $(".myTuiHuan");
        myTuiHuan.show();
        myTuiHuan.siblings().hide();
        //刷新并显示退换记录
        build_exchangeRecord();
    });
    //点击发起退换申请按钮
    $("#addExchange").click(function(){
        $("#exchangeCar tbody").empty();
        $.ajax({
            url: "getUserCars",
            data: "",
            type: "GET",
            success: function (result) {
                $("#recordTab tbody").empty();
                $.each(result, function (index, item) {
                    var carId = $("<td></td>").append(item.usernewcarno==null?item.usersecondcarno:item.usernewcarno);
                    var uptDate = $("<td></td>").append(item.uptdate);
                    var checkbox = $("<input type='radio' name='usrcarid'/>");
                    checkbox.val(carId);
                    var checkboxTag = $("<td></td>").append(checkbox);
                    $("<tr></tr>").append(carId)
                        .append(uptDate)
                        .append(checkboxTag)
                        .appendTo("#exchangeCar tbody");
                });
            }
        });
    });

    //点击提交退换按钮
    $("#submitExchange").click(function(){
        var carNo = $("input:radio[name='usrcarid']:checked").parent().parent().children(0).text();
        var reason = $("#exchangeReason").val();
        if(carNo==""||reason==""){
            return false;
        }else{
        $.ajax({
            url: "addExchangeRecord",
            data: {"carNo":carNo.substring(0,12),"reason":reason},
            type: 'GET',
            dataType: 'json',
            contentType: 'application/json;charset=utf-8',
            success: function (result) {
                if(result==1){
                    alert("成功!");
                    build_exchangeRecord();
                }else if(result==2){
                    alert("该车辆已提交过申请，请勿重复提交!");
                }else{
                    alert("失败，请重试！");
                }
            }
        });
        }
    });

    //反馈和投诉
    $("#myFeedBack").click(function () {
        var myFeedBack = $(".myFeedBack");
        myFeedBack.show();
        myFeedBack.siblings().hide();
        //刷新并显示反馈与投诉
        build_feedbackRecord();
    });

    //点击提交投诉和反馈按钮
    $("#submitFeedback").click(function(){
        var topic = $("#feedbackTopic").val();
        var content = $("#feedbackContent").val();
        if(topic==""||content==""){
            return false;
        }else{
            $.ajax({
                url: "addFeedbackRecord",
                data: {"topic":topic,"fbcontends":content},
                type: "GET",
                dataType: 'json',
                contentType: 'application/json;charset=utf-8',
                success: function (result) {
                    if(result===1){
                        alert("提交成功！请耐心等待处理！");
                        //刷新并显示反馈与投诉
                        build_feedbackRecord();
                    }else{
                        alert("提交失败，请稍后再试！");
                    }
                }
            });
        }
    });

    var prevurl = document.referrer; // 获取上一个页面的url地址
    //如果上一页面是全款买车
    if (prevurl.search(/toBuyByAml3/) > 0) {
        if (confirm("确认查看购车进度？")) {
            var myBuyCar = $(".myBuyCar");
            myBuyCar.show();
            myBuyCar.siblings().hide();

        } else {
            self.location = "newCarDetail";
        }
    }


});

//刷新显示登陆日志表
function build_LoginRecord() {
    $.ajax({
        url: "loginRecord",
        data: "",
        type: "GET",
        success: function (result) {
            $("#recordTab tbody").empty();
            $.each(result, function (index, item) {
                var ip = $("<td></td>").append(item.loginip);
                var time = $("<td></td>").append(item.logintime);
                var delbtn = $("<button></button>").addClass("btn btn-danger btn-sm delLoginRecordBtn")
                    .append($("<span></span>").addClass("glyphicon glyphicon-trash")).append("删除");
                //为删除按钮添加一个自定义的属性来表示当前删除的 id
                delbtn.attr("del-id", item.recoredno);
                var btnTad = $("<td></td>").append(delbtn);
                $("<tr></tr>").append(ip)
                    .append(time)
                    .append(btnTad)
                    .appendTo("#recordTab tbody");
            });
        }
    });
}

//日志删除按钮
$(document).on("click", ".delLoginRecordBtn", function () {
    //1、弹出是否确认删除对话框
    var recordNo = $(this).attr("del-id");
    if (confirm("确认删除该条日志吗？")) {
        //确认，发送ajax请求删除
        $.ajax({
            url: "delLoginRecord",
            type: "POST",
            data: "recordNo=" + recordNo,
            success: function (result) {
                //刷新显示日志表
                build_LoginRecord();
            }
        });
    }
});

//刷新并显示信用资料
function build_MyCreditFiles() {
    $.ajax({
        url: "creditFiles",
        data: "",
        type: "GET",
        success: function (result1) {
            $("#creditFileTab tbody").empty();
            $.each(result1, function (index, item) {
                var fileA =$("<a target='_blank'></a>").attr("href",item.filesrc).append(item.filename);
                var file = $("<td></td>").append(fileA);
                var filename = $("<td></td>").append(item.filename);
                var time = $("<td></td>").append(item.sendtime);
                var topic = $("<td></td>").append(item.topic);
                const delbtn = $("<button></button>").addClass('btn btn-danger btn-sm delCreditFileBtn')
                    .append($("<span></span>").addClass("glyphicon glyphicon-trash")).append("删除");
                //为删除按钮添加一个自定义的属性来表示当前删除的 id
                delbtn.attr("del-id", item.creaditfileno);
                var btnTad = $("<td></td>").append(delbtn);
                $("<tr></tr>").append(file)
                    .append(filename)
                    .append(time)
                    .append(topic)
                    .append(btnTad)
                    .appendTo("#creditFileTab tbody");
            });
        }
    });
}


//删除信用资料
$(document).on("click", ".delCreditFileBtn", function () {
    //1.弹出是否确认删除信用资料
    var delfileNo = $(this).attr("del-id");
    if (confirm("确认删除这个信用资料吗？")) {
        //2.确认，发送ajax请求删除
        $.ajax({
            url: "delCreditFile",
            type: "POST",
            data: "creditFileNo=" + delfileNo,
            success: function (result) {
                if(result===1){
                    alert("删除成功！");
                    //刷新并显示信用资料
                    build_MyCreditFiles();
                }else{
                    alert("删除失败！")
                }
            }
        });
    }
});



//刷新并显示分期还款记录
function build_instRecord() {
    $("#instRecordTab tbody").empty();
    $.ajax({
        url: "instRecords",
        data: "",
        type: "GET",
        success: function (result2) {
            $.each(result2, function (index, item) {
                var orderNum = $("<td></td>").append(index+1);
                var date = $("<td></td>").append(item.repaymentdate);
                var money = $("<td></td>").append(item.repaymentmoney);
                var lastmoney = $("<td></td>").append(item.lastmoney);
                $("<tr></tr>").append(orderNum)
                    .append(date)
                    .append(money)
                    .append(lastmoney)
                    .appendTo("#instRecordTab tbody");
            });
        }
    });
}
//刷新并显示维保记录
function build_maintainRecord() {
    $.ajax({
        url: "maintainRecords",
        data: "",
        type: "GET",
        success: function (result3) {
            $("#maintainRecordTab tbody").empty();
            $.each(result3, function (index, item) {
                var carInfo = $("<td></td>").append(item.carno);
                var items = $("<td></td>").append(item.maintainitem);
                var money = $("<td></td>").append(item.price);
                var employee = $("<td></td>").append(item.employeeno);
                var date = $("<td></td>").append(item.maintaindate);
                $("<tr></tr>").append(carInfo)
                    .append(items)
                    .append(money)
                    .append(employee)
                    .append(date)
                    .appendTo("#maintainRecordTab tbody");
            });
        }
    });
}
//刷新并显示退换记录
function build_exchangeRecord() {
    $.ajax({
        url: "exchangeRecords",
        data: "",
        type: "GET",
        success: function (result4) {
            $("#ExchangeRecordTab tbody").empty();
            $.each(result4, function (index, item) {
                var carInfo = $("<td></td>").append(item.carno);
                var applyreason = $("<td></td>").append(item.exchangereason);
                var applydate = $("<td></td>").append(item.applydate);
                var state = $("<td></td>").append(item.state);
                var result = $("<td></td>").append(item.auditresult);
                var exchangedate = $("<td></td>").append(item.exchangeddate);
                $("<tr></tr>").append(carInfo)
                    .append(applyreason)
                    .append(applydate)
                    .append(state)
                    .append(result)
                    .append(exchangedate)
                    .appendTo("#ExchangeRecordTab tbody");
            });
        }
    });
}
//刷新并显示投诉反馈记录
function build_feedbackRecord() {
    $("#feedBackRecordTab tbody").empty();
    $.ajax({
        url: "userFeedbackRecords",
        data: "",
        type: "GET",
        success: function (result5) {
            $.each(result5, function (index, item) {
                var topic = $("<td></td>").append(item.topic);
                var fbcontents = $("<td></td>").append(item.fbcontents);
                var sendtime = $("<td></td>").append(item.sendtime);
                var result = $("<td></td>").append(item.handleresult);
                var handletime = $("<td></td>").append(item.handletime);
                const delbtn = $("<button></button>").addClass('btn btn-danger btn-sm delFeedbackBtn')
                    .append($("<span></span>").addClass("glyphicon glyphicon-trash")).append("删除");
                delbtn.attr("del-id", item.feedbackno);
                var btnTad = $("<td></td>").append(delbtn);
                $("<tr></tr>").append(topic)
                    .append(fbcontents)
                    .append(sendtime)
                    .append(result)
                    .append(handletime)
                    .append(btnTad)
                    .appendTo("#feedBackRecordTab tbody");
            });
        }
    });
}
//删除投诉反馈
$(document).on("click", ".delFeedbackBtn", function () {
    //1、弹出是否确认删除对话框
    var feedbackNo = $(this).attr("del-id");
    if (confirm("确认删除该条投诉反馈吗？")) {
        //确认，发送ajax请求删除
        $.ajax({
            url: "delFeedbackRecord",
            type: "POST",
            data: "fbid=" + feedbackNo,
            success: function (result) {
                //刷新显示日志表
                build_feedbackRecord();
            }
        });
    }
});

